import * as React from 'react';
import { Input, Icon, AutoComplete } from 'antd';
import * as classNames from 'classnames';
import './header-search.less';

interface HeaderSearchProps {
  defaultOpen: boolean;
  placeholder?: string;
  dataSource: string[];
  className?: string;
  onSearch?: (val: string) => void;
  onChange?: () => void;
  onPressEnter?: (val: string) => void;
  style?: React.CSSProperties;
}

interface HeaderSearchState {
  searchMode: boolean;
  value: string;
}

export default class HeaderSearch extends React.Component<HeaderSearchProps, HeaderSearchState> {
  timeout: any;
  input: any;
  static defaultProps: HeaderSearchProps = {
    onPressEnter: () => {},
    onSearch: () => {},
    className: '',
    placeholder: '',
    dataSource: [],
    defaultOpen: false,
  };
  constructor(props: HeaderSearchProps) {
    super(props);
    this.state = {
      searchMode: props.defaultOpen,
      value: '',
    };
  }

  componentWillUnmount() {
    clearTimeout(this.timeout);
  }
  onKeyDown = (e: any) => {
    if (e.key === 'Enter') {
      this.timeout = setTimeout(() => {
        if (this.props.onPressEnter) this.props.onPressEnter(this.state.value);
      }, 0);
    }
  };
  onChange = (value: string) => {
    this.setState({ value });
    if (this.props.onChange) {
      this.props.onChange();
    }
  };
  enterSearchMode = () => {
    this.setState({ searchMode: true }, () => {
      if (this.state.searchMode) {
        this.input.focus();
      }
    });
  };
  leaveSearchMode = () => {
    this.setState({
      searchMode: false,
      value: '',
    });
  };
  render() {
    const { className, placeholder, ...restProps } = this.props;
    const inputClass = classNames('input', this.state.searchMode ? 'show' : '');
    return (
      <span className={classNames(className, 'header-search')} onClick={this.enterSearchMode}>
        <Icon type="search" key="Icon" />
        <AutoComplete
          key="AutoComplete"
          {...restProps}
          className={inputClass}
          value={this.state.value}
          onChange={this.onChange}>
          <Input
            placeholder={placeholder}
            ref={node => {
              this.input = node;
            }}
            onKeyDown={this.onKeyDown}
            onBlur={this.leaveSearchMode}
          />
        </AutoComplete>
      </span>
    );
  }
}
